package com.basin.common.core.advice;

import com.basin.common.core.exception.BasinException;
import com.basin.common.core.response.Resp;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Hidden
@RestControllerAdvice
@Slf4j(topic = "BASIN:CORE:GLOBAL_EXCEPTION_ADVICE")
public class GlobalExceptionAdvice {
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Resp<String> handleArgumentValidException(MethodArgumentNotValidException e) {
        log.error("全局异常处理器-MethodArgumentNotValidException：{}", e.getMessage(), e);
        // 获取default message
        return Resp.fail(400, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = {BasinException.class})
    public Resp<String> handleBasinException(BasinException e) {
        log.error("全局异常处理器-BasinException：{}", e.getMessage(), e);
        return Resp.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {SQLException.class})
    public Resp<String> handleSqlException(SQLException e) {
        log.error("全局异常处理器-SQLException：{}", e.getMessage(), e);
        return Resp.fail(500, "SQL错误 {" + e.getMessage() + "}");
    }

    @ExceptionHandler(value = {Exception.class})
    public Resp<String> handleException(Exception e) {
        log.error("全局异常处理器-Exception：{}", e.getMessage(), e);
        return Resp.fail(500, "系统错误 {" + e.getMessage() + "}");
    }
}
